package com.negative.activities;

import java.util.ArrayList;

import com.negative.data.EventItem;
import com.negative.logic.DialogManager;
import com.negative.utils.APIHelper;
import com.negative.utils.IOHelper;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.widget.ProgressBar;

public class SplashScreen extends Activity {

	NegativeApplication app;
	APIHelper api;
	ProgressBar progressBar;
	Activity activity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splashscreen);

		activity = this;
		app = (NegativeApplication) getApplication();
		progressBar = (ProgressBar) findViewById(R.id.splashProgressBar);
		Thread getEventsThread = new Thread() {
			public void run() {
				IOHelper.getAdsFromGoogleDoc(app);
				api = new APIHelper();
				IOHelper.getCredFromGoogleDoc(api);
				long before = SystemClock.elapsedRealtime();
				ArrayList<EventItem> events = null;
				try {
					events = api.getEventList();

					app.setEventList(events);
					try {
						long gap = SystemClock.elapsedRealtime() - before;
						if (gap < 2000)
							sleep(2000 - gap);
					} catch (InterruptedException e) {

					}
					if (events.isEmpty() == false) {
						Intent intent;
						String adUrl = getRandomAdUrl();
						if (adUrl != null) {
							intent = new Intent(SplashScreen.this,
									AdActivity.class);
							intent.putExtra("URL", adUrl);
						} else {
							intent = new Intent(SplashScreen.this,
									MainMenu.class);
						}
						startActivity(intent);
					} else {
						DialogManager.showOKDialog(activity, true,
								getString(R.string.info),
								getString(R.string.no_events_message));
						Intent intent = new Intent(SplashScreen.this,
								PurchaseListActivity.class);
						startActivity(intent);
					}
				} catch (Exception e1) {
					events = new ArrayList<EventItem>();

					app.setEventList(events);
					DialogManager.showOKDialog(activity, true,
							getString(R.string.error),
							getString(R.string.internet_error));
					Intent intent = new Intent(SplashScreen.this,
							PurchaseListActivity.class);
					startActivity(intent);
				}
				finish();
			}
		};
		getEventsThread.start();
	}

	private String getRandomAdUrl() {
		String url = null;
		NegativeApplication app = (NegativeApplication) getApplication();
		if (app.getAdUrls().size() != 0) {
			int index = (int) (Math.random() * (app.getAdUrls().size() - 1));
			url = app.getAdUrls().get(index);
		}
		return url;
	}
}
